import { JSEncrypt } from "jsencrypt";
import CryptoJS from "crypto-js";
import NodeRSA from "node-rsa";

/**
 * 格式化获取的服务端RSA公钥
 */
export function HandleServerRSAKey(serverKey) {
  return "-----BEGIN PUBLIC KEY-----" + serverKey + "-----END PUBLIC KEY-----";
}

export function HandleServerPriRSAKey(serverKey) {
  return (
    "-----BEGIN PRIVATE KEY-----" + serverKey + "-----END PRIVATE KEY-----"
  );
}

/**
 * 处理客户端RSA密钥格式
 */
export function HandleLocalRSAKey(localKey) {
  return localKey.replace(/\r|\n/g, "").split("-----")[2];
}

/**
 * 客户端生成RSA公钥私钥对 引用node-rsa工具
 */
export function generateClientRSAKeyPair() {
  //生成1024位的密钥
  const nodeRSAKey = new NodeRSA({ b: 1024 });
  // 导出公钥
  const clientRSAPublicKey = nodeRSAKey.exportKey("pkcs8-public-pem");
  // 导出私钥
  const clientRSAPrivateKey = nodeRSAKey.exportKey("pkcs8-private-pem");
  // return { clientRSAPublicKey, clientRSAPrivateKey };
  return {
    clientRSAPublicKey: HandleLocalRSAKey(clientRSAPublicKey),
    clientRSAPrivateKey: HandleLocalRSAKey(clientRSAPrivateKey),
  };
}

/**
 * RSA公钥加密
 * @param {String} publicKey
 * @param {*} data
 */
export function RSAPublicKeyEncrypt(publicKey, data) {
  // var nodersa = new NodeRSA(publicKey);
  // nodersa.setOptions({ encryptionScheme: 'pkcs8' });
  // return nodersa.encrypt(data, 'base64');
  if (!publicKey) {
    return data;
  }
  const encryptStr = new JSEncrypt();
  encryptStr.setPublicKey(publicKey);
  return encryptStr.encrypt(data);
}

/**
 * RSA私钥解密
 * @param {String} privateKey
 * @param {String} data
 */
export function RSAPrivateKeyDecrypt(privateKey, data) {
  if (!privateKey) {
    return data;
  }
  const decrypt = new JSEncrypt();
  decrypt.setPrivateKey(privateKey);
  return decrypt.decrypt(data);
  // const nodersa = new NodeRSA(privateKey);
  // return nodersa.decrypt(data, 'utf8');
}

/**
 * RSA 私钥加密
 * @param {*} privateKey
 * @param {*} data
 */
export function RSAPrivateKeyEncrypt(privateKey, data) {
  if (!privateKey) {
    return data;
  }
  const key = new NodeRSA({ b: 1024 });
  key.importKey(privateKey, "pkcs8-private-pem");
  return key.encryptPrivate(data, "base64", "utf8");
  // var encrypt = new JSEncrypt()
  // encrypt.setPrivateKey(privateKey)
  // return encrypt.encrypt(data)
}

/**
 * 随机生成指定数量的16进制key
 * @param {Number} num
 */
export function generatekey(num) {
  const library =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let key = "";
  for (let i = 0; i < num; i++) {
    let randomPoz = Math.floor(Math.random() * library.length);
    key += library.substring(randomPoz, randomPoz + 1);
  }
  return key;
}

/**
 * AES 加密
 * @param {String} dataStr
 * @param {String} aesKey
 */
export function AesEncrypt(dataStr, aesKey) {
  if (!dataStr || !aesKey) {
    return "";
  }
  const key = CryptoJS.enc.Utf8.parse(aesKey);
  const srcs = CryptoJS.enc.Utf8.parse(dataStr);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
}

/**
 * AES 解密
 * @param {String} dataStr
 * @param {String} aesKey
 */
export function AesDecrypt(dataStr, aesKey) {
  if (!dataStr || !aesKey) {
    return "";
  }
  const key = CryptoJS.enc.Utf8.parse(aesKey);
  const decrypt = CryptoJS.AES.decrypt(dataStr.toString(), key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

/**
 * MD5 加密
 * @param {Object} data
 */
export function MD5Encrypt(data) {
  return CryptoJS.MD5(JSON.stringify(data)).toString();
}

/**
 * 获取加密字符串
 * @param {Object} object
 * @param {String} pubKey
 */
export function EncryptedJson(object, priKey, pubKey) {
  if (!object) {
    return {};
  }
  if (!pubKey) {
    return object;
  }
  const md5 = MD5Encrypt(object);
  const enmd5 = RSAPrivateKeyEncrypt(priKey, md5);
  // console.log(enmd5);

  // let key = new NodeRSA({ b: 1024 });
  // key.importKey(object.pubKey, 'pkcs8-public-pem');
  // let decryptData = key.decryptPublic(enmd5, 'utf8');
  // console.log('\n公钥解密后的数据：\n', decryptData);

  // 获取16位随机数,当做aes秘钥key
  const randomStr = generatekey(16);
  // console.log(randomStr)
  // aes加密
  const data = AesEncrypt(JSON.stringify(object), randomStr);
  // console.log(data)
  // rsa加密
  const encrypted = RSAPublicKeyEncrypt(pubKey, randomStr);
  // console.log(encrypted, pubKey);
  // 创建json对象
  const json = {
    md5: enmd5,
    data: data,
    aes: encrypted,
  };
  return json;
}

/**
 * 测试用例
 * @param {*} priKey
 * @param {*} pubK
 */
export function testFun(priKey, pubK) {
  if (priKey) {
    var key = new NodeRSA({ b: 1024 });
    key.importKey(priKey, "pkcs8-private-pem");
    var encryData = key.encryptPrivate(
      "服务端测试 -> jameszou love code~~~",
      "base64",
      "utf8"
    );
  }
  if (pubK) {
    key.importKey(pubK, "pkcs8-public-pem");
    var decryptData = key.decryptPublic(encryData, "utf8");
  }

  // let data = "sxsdsdsdsdssds";
  // const nodersa = new NodeRSA(priKey);
  // nodersa.setOptions({ encryptionScheme: 'pkcs8-private-pem' });
  // const encrypted = nodersa.encrypt(data, 'base64');
  // const nodersa2 = new NodeRSA(pubK);
  // const decrypted = nodersa2.decrypt(encrypted, 'utf8');
  // console.log(decrypted)
}

/**
 * 解密字符串
 * @param {String} aesData
 * @param {String} rsaData
 * @param {String} priKey
 */
export function DecryptedJson(aesData, rsaData, priKey) {
  // console.log("AES DATA: ", aesData);
  // aes解密
  const aesKey = RSAPrivateKeyDecrypt(priKey, aesData);
  // console.log("AES KEY: ",aesKey);
  // rsa解密
  const data = AesDecrypt(rsaData, aesKey);
  // console.log("Response Data: ", data)
  if (!data) {
    return { message: "请求异常，请重新登录" };
  }
  // return JSON.parse(data);
  const obj = JSON.parse(data);
  return obj;
}
